/**
 * description：
 * author：洪俊勇
 * createTime：2017/9/20
 * version:1.0.0.0
 * history:
 *   1、
 *   2、
 */
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var CommentSchema = new Schema({
    movie: {type: ObjectId, ref: 'Movie'},
    from: {type: ObjectId, ref: 'User'},
    reply:[{
        from: {type: ObjectId, ref: 'User'},
        to: {type: ObjectId, ref: 'User'},
        content: String,
    }],
    content: String,
    meta: {
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    }
});

/**
 * 每次存储的时候都来调用这个方法
 */
CommentSchema.pre('save', function (next) {
    if (this.isNew) {//判断数据是否新加的
        this.meta.createAt = this.meta.updateAt = Date.now();
    } else {
        this.meta.updateAt = Date.now();
    }

    // 让存储流程继续走下去
    next()
});


CommentSchema.statics = {
    /**
     * 取出数据库中所有数据
     * @param cb
     * @returns {Promise|Array|{index: number, input: string}|*|{npmUpdate}}
     */
    fetch: function (cb) {
        return this
            .find({})
            .sort('meta.updateAt')
            .exec(cb)
    },
    /**
     * 根据id查询
     * @param id
     * @param cb
     * @returns {Promise}
     */
    findById: function (id, cb) {
        return this
            .findOne({_id: id})
            .exec(cb)
    }
};

//把模式导出
module.exports = CommentSchema;
